import {AddressModel} from "../../../database/models/address";
import {GamePrizeModel} from "../../../database/models/gamePrize";
import {PlayerModel} from "../../../database/models/player";
import {ProductModel} from "../../../database/models/Product";
import moment = require("moment");

export const typeDefs = `

  type Address{
    _id: String!
    province:String!
    city: String!
    area: String!
    street: String!
    detail: String!
    receiver: String!
    phone: String!
    defualt: Boolean
    createAt: String!
  }

  type GamePrize{
    _id: String!
    player:Player!
    product: Product
    productName: String!
    productUrl: String!
    state: String!
    createAt: String!
    deliveryId: String
    requestDeliveryAt: String
    toAddress: Address
    from: String!
  }
`

export const queryDefs = `
  allGamePrizeByDate(date: String): [GamePrize]
  getGamePrizeByDateAndState(date: String, state:String!): [GamePrize]
  getGamePrizeByStates(states:[String!]!): [GamePrize]
  getGamePrizeByPlayer(_id:String!):[GamePrize]!
`


export const mutationDefs = `
  setGameDelivery(_id:String!, deliveryId: String!): GamePrize
`

export const resolvers = {
  Query: {
    async getGamePrizeByPlayer(_, {_id}) {
      return GamePrizeModel.find({
        player: _id
      }).sort({requestDeliveryAt: -1, createAt: -1})
    },

    async allGamePrizeByDate(_, {date}) {
      const beg = moment(date).startOf('day').toDate()
      const end = moment(date).endOf('day').toDate()

      return GamePrizeModel.find({
        $or: [
          {createAt: {$gte: beg, $lt: end}},
          {requestDeliveryAt: {$gte: beg, $lt: end}}
        ]
      }).sort({requestDeliveryAt: -1, createAt: -1})
    },
    async getGamePrizeByDateAndState(_, {date, state}) {

      const beg = moment(date).startOf('day').toDate()
      const end = moment(date).endOf('day').toDate()

      let c = {}
      if (state === 'idle') {
        c = {
          createAt: {$gte: beg, $lt: end},
        }
      } else {
        c = {
          requestDeliveryAt: {$gte: beg, $lt: end},
        }
      }

      return GamePrizeModel.find({
        ...c,
        state
      }).sort({requestDeliveryAt: -1})
    },
    async getGamePrizeByStates(_, {states}) {
      return GamePrizeModel.find({
        state: {$in: states}
      }).sort({createAt: -1})
    }

  },

  GamePrize: {
    player({player}) {
      return PlayerModel.findById(player)
    },
    product({product}) {
      return ProductModel.findById(product)
    },
    toAddress({address}) {
      AddressModel.findById(address)
      return
    }
  }


}
